﻿using System;

namespace ESoft.Core.Utils.Extensions
{
    public static class DecimalExtensions
    {
        internal static string GetNum2StrFormatter(int precision)
        {
            return precision == 0 ? "{0:0.#}" : "{0:0." + "0".Replicate(precision) + "}";
        }

        /// <summary>
        ///     保留多少位小数格式化输出
        /// </summary>
        /// <param name="numbericValue">The numberic value.</param>
        /// <param name="precision">The precision.</param>
        /// <returns>System.String.</returns>
        public static string ToStringWithPrecision(this decimal numbericValue, int precision = 2)
        {
            return string.Format(GetNum2StrFormatter(precision), numbericValue);
        }

        /// <summary>
        ///     判断两个数值相同精度时内容是否相等
        /// </summary>
        /// <param name="numbericValue">The numberic value.</param>
        /// <param name="otherValue">The other value.</param>
        /// <param name="precision">The precision.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool EqualsBySpecifiedPrecision(this decimal numbericValue, decimal otherValue,
            int precision = 2)
        {
            return string.Format(GetNum2StrFormatter(precision), numbericValue)
                .Equals(string.Format(GetNum2StrFormatter(precision), otherValue));
        }

        /// <summary>
        ///     获取正常格式化值
        ///     0.1100M=>0.11M
        /// </summary>
        /// <param name="value">The value to normalize.</param>
        /// <returns>The normalized value.</returns>
        /// <remarks>
        ///     Normalizing changes the scaling factor and removes trailing zeroes,
        ///     so 1.2500m comes out as 1.25m.
        /// </remarks>
        public static decimal Normalize(this decimal value)
        {
            return value / 1.000000000000000000000000000000000m;
        }
    }
}